package cn.sjxy.service;

import cn.sjxy.baseLib.SjuException;
import cn.sjxy.mapper.Mp_BookInfo;
import cn.sjxy.mapper.Mp_OrderDetail;
import cn.sjxy.mapper.Mp_OrderInfo;
import cn.sjxy.mapper.Mp_Shopping;
import cn.sjxy.mapper.Mp_User;
import cn.sjxy.model.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单业务逻辑层
 */
@Service
public class Sv_OrderInfo {

    @Autowired
    private Mp_OrderInfo mp_orderInfo;

    @Autowired
    private Mp_OrderDetail mp_orderDetail;

    @Autowired
    private Mp_BookInfo mp_bookInfo;

    @Autowired
    private Mp_Shopping mp_shopping;

    @Autowired
    private Mp_User mp_user;

    /**
     * 图书详情页直接购买下单
     * @param userCode
     * @param bookCode
     * @param buyQty
     * @param receiveUser
     * @param receivePhone
     * @param receiveAddress
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void bookOrder(String userCode, String bookCode, Integer buyQty,
                          String receiveUser, String receivePhone, String receiveAddress) throws Exception {
        // 查询图书信息
        QueryWrapper<Md_BookInfo> bookWrapper = new QueryWrapper<>();
        bookWrapper.eq("bookCode", bookCode);
        Md_BookInfo bookInfo = mp_bookInfo.selectOne(bookWrapper);

        if (bookInfo == null) {
            SjuException.appEx("图书不存在");
        }

        if (!"是".equals(bookInfo.getIsSell())) {
            SjuException.appEx("该图书已下架");
        }

        // 生成订单编号
        String orderCode = UUID.randomUUID().toString().replace("-", "");

        // 计算总金额
        BigDecimal totalMoney = bookInfo.getSellPrice().multiply(new BigDecimal(buyQty));

        // 创建订单信息
        Md_OrderInfo orderInfo = new Md_OrderInfo();
        orderInfo.setOrderCode(orderCode);
        orderInfo.setOrderDate(new Date());
        orderInfo.setUserCode(userCode);
        orderInfo.setTotalMoney(totalMoney);
        orderInfo.setReceiveUser(receiveUser);
        orderInfo.setReceivePhone(receivePhone);
        orderInfo.setReceiveAddress(receiveAddress);
        orderInfo.setIsPay("是");  // 默认已付款
        orderInfo.setPayDate(new Date());
        orderInfo.setIsSend("否");
        orderInfo.setIsReceive("否");

        mp_orderInfo.insert(orderInfo);

        // 创建订单明细
        Md_OrderDetail orderDetail = new Md_OrderDetail();
        orderDetail.setOrderCode(orderCode);
        orderDetail.setBookCode(bookCode);
        orderDetail.setBuyPrice(bookInfo.getSellPrice());
        orderDetail.setBuyQty(buyQty);

        mp_orderDetail.insert(orderDetail);

        // 更新图书销量
        bookInfo.setTotalSellQty(bookInfo.getTotalSellQty() == null ? buyQty : bookInfo.getTotalSellQty() + buyQty);
        mp_bookInfo.updateById(bookInfo);
    }

    /**
     * 购物车下单
     * @param userCode
     * @param bookCodeList
     * @param receiveUser
     * @param receivePhone
     * @param receiveAddress
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void shopOrder(String userCode, List<String> bookCodeList,
                          String receiveUser, String receivePhone, String receiveAddress) throws Exception {
        // 查询购物车中的商品
        QueryWrapper<Md_Shopping> shoppingWrapper = new QueryWrapper<>();
        shoppingWrapper.eq("userCode", userCode);
        shoppingWrapper.in("bookCode", bookCodeList);
        List<Md_Shopping> shoppingList = mp_shopping.selectList(shoppingWrapper);

        if (shoppingList == null || shoppingList.isEmpty()) {
            SjuException.appEx("购物车中没有选中的商品");
        }

        // 生成订单编号
        String orderCode = UUID.randomUUID().toString().replace("-", "");

        // 计算总金额
        BigDecimal totalMoney = BigDecimal.ZERO;

        // 创建订单明细
        for (Md_Shopping shopping : shoppingList) {
            // 查询图书信息
            QueryWrapper<Md_BookInfo> bookWrapper = new QueryWrapper<>();
            bookWrapper.eq("bookCode", shopping.getBookCode());
            Md_BookInfo bookInfo = mp_bookInfo.selectOne(bookWrapper);

            if (bookInfo == null) {
                SjuException.appEx("图书【" + shopping.getBookCode() + "】不存在");
            }

            if (!"是".equals(bookInfo.getIsSell())) {
                SjuException.appEx("图书【" + bookInfo.getBookName() + "】已下架");
            }

            // 创建订单明细
            Md_OrderDetail orderDetail = new Md_OrderDetail();
            orderDetail.setOrderCode(orderCode);
            orderDetail.setBookCode(shopping.getBookCode());
            orderDetail.setBuyPrice(bookInfo.getSellPrice());
            orderDetail.setBuyQty(shopping.getBuyQty());

            mp_orderDetail.insert(orderDetail);

            // 累加总金额
            totalMoney = totalMoney.add(bookInfo.getSellPrice().multiply(new BigDecimal(shopping.getBuyQty())));

            // 更新图书销量
            bookInfo.setTotalSellQty(bookInfo.getTotalSellQty() == null ? shopping.getBuyQty() : bookInfo.getTotalSellQty() + shopping.getBuyQty());
            mp_bookInfo.updateById(bookInfo);
        }

        // 创建订单信息
        Md_OrderInfo orderInfo = new Md_OrderInfo();
        orderInfo.setOrderCode(orderCode);
        orderInfo.setOrderDate(new Date());
        orderInfo.setUserCode(userCode);
        orderInfo.setTotalMoney(totalMoney);
        orderInfo.setReceiveUser(receiveUser);
        orderInfo.setReceivePhone(receivePhone);
        orderInfo.setReceiveAddress(receiveAddress);
        orderInfo.setIsPay("是");  // 默认已付款
        orderInfo.setPayDate(new Date());
        orderInfo.setIsSend("否");
        orderInfo.setIsReceive("否");

        mp_orderInfo.insert(orderInfo);

        // 删除购物车中已下单的商品
        mp_shopping.delete(shoppingWrapper);
    }

    /**
     * 获取订单详情（包含订单明细）
     * @param orderCode
     * @return
     */
    public Md_OrderInfo getOrderDetail(String orderCode) {
        QueryWrapper<Md_OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("orderCode", orderCode);
        Md_OrderInfo orderInfo = mp_orderInfo.selectOne(wrapper);

        if (orderInfo != null) {
            // 查询用户名称
            QueryWrapper<Md_User> userWrapper = new QueryWrapper<>();
            userWrapper.eq("userCode", orderInfo.getUserCode());
            Md_User user = mp_user.selectOne(userWrapper);
            if (user != null) {
                orderInfo.setUserName(user.getUserName());
            }
        }

        return orderInfo;
    }

    /**
     * 获取订单明细列表
     * @param orderCode
     * @return
     */
    public List<Md_OrderDetail> getOrderDetailList(String orderCode) {
        QueryWrapper<Md_OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("orderCode", orderCode);
        List<Md_OrderDetail> detailList = mp_orderDetail.selectList(wrapper);

        // 填充图书名称
        for (Md_OrderDetail detail : detailList) {
            QueryWrapper<Md_BookInfo> bookWrapper = new QueryWrapper<>();
            bookWrapper.eq("bookCode", detail.getBookCode());
            Md_BookInfo bookInfo = mp_bookInfo.selectOne(bookWrapper);
            if (bookInfo != null) {
                detail.setBookName(bookInfo.getBookName());
            }
        }

        return detailList;
    }

    /**
     * 确认收货
     * @param orderCode
     * @param userCode
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceive(String orderCode, String userCode) throws Exception {
        QueryWrapper<Md_OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("orderCode", orderCode);
        wrapper.eq("userCode", userCode);
        Md_OrderInfo orderInfo = mp_orderInfo.selectOne(wrapper);

        if (orderInfo == null) {
            SjuException.appEx("订单不存在");
        }

        if (!"是".equals(orderInfo.getIsSend())) {
            SjuException.appEx("订单还未发货");
        }

        if ("是".equals(orderInfo.getIsReceive())) {
            SjuException.appEx("订单已确认收货");
        }

        orderInfo.setIsReceive("是");
        orderInfo.setReceiveDate(new Date());
        mp_orderInfo.updateById(orderInfo);
    }

    /**
     * 管理员发货
     * @param orderCode
     * @param sendNo
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendOrder(String orderCode, String sendNo) throws Exception {
        QueryWrapper<Md_OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("orderCode", orderCode);
        Md_OrderInfo orderInfo = mp_orderInfo.selectOne(wrapper);

        if (orderInfo == null) {
            SjuException.appEx("订单不存在");
        }

        if (!"是".equals(orderInfo.getIsPay())) {
            SjuException.appEx("订单还未付款");
        }

        if ("是".equals(orderInfo.getIsSend())) {
            SjuException.appEx("订单已发货");
        }

        orderInfo.setIsSend("是");
        orderInfo.setSendDate(new Date());
        orderInfo.setSendNo(sendNo);
        mp_orderInfo.updateById(orderInfo);
    }
}

